package com.neborosoft.android.events;

import com.neborosoft.FlyingDog.android.MyActivity;
import com.neborosoft.lib.API_8.Collections;
import com.neborosoft.lib.threading.AsyncTimer;
import com.neborosoft.lib.threading.OnHostThreadExecutor;

import java.util.HashSet;
import java.util.Set;

/**
 * Project: FlyingDog
 * User: stikhonenko
 * Date: 12/12/12
 * Time: 2:51 PM
 */
public class EventManager {
    private static EventManager instance;

    private Set<Event> renderingEvents = Collections.synchronizedSet(new HashSet<Event>());
    private Set<Event> backgroundEvents = Collections.synchronizedSet(new HashSet<Event>());
    private static final int TIMER_DELAY = 30;
    private AsyncTimer timer;
    private OnHostThreadExecutor onHostThreadExecutor;

    public static void init(OnHostThreadExecutor onHostThreadExecutor){
        instance = new EventManager();
        instance.onHostThreadExecutor = onHostThreadExecutor;
    }

    public static EventManager getInstance(){
        if(instance == null){
            throw new IllegalStateException("call init before getInstance");
        }

        return instance;
    }

    private Runnable eventsRunningAction = new Runnable() {
        @Override
        public void run() {
            for(final Event event : backgroundEvents){
                event.run();
            }

            for(final Event event : renderingEvents){
                onHostThreadExecutor.runOnHostThread(new Runnable() {
                    @Override
                    public void run() {
                        event.run();
                    }
                });
            }
        }
    };

    private EventManager(){
        timer = new AsyncTimer(eventsRunningAction);
        timer.start(TIMER_DELAY);
    }

    public void addRenderingEvent(Event event){
        renderingEvents.add(event);
    }

    public void removeRenderingEvent(Event event){
        renderingEvents.remove(event);
    }

    public void addBackgroundEvent(Event event){
        backgroundEvents.add(event);
    }

    public void removeBackgroundEvent(Event event){
        backgroundEvents.remove(event);
    }

    public void removeEvent(Event event){
        removeBackgroundEvent(event);
        removeRenderingEvent(event);
    }
}
